# @Data  : 2020/01/02 19:04
# @Author: xushibo
# @File  : CardInfoByTxt.py

import os

TITLE = ['ICCID', 'IMSI', 'KI', 'ESN', 'PIN1', 'PUK1', 'PIN2', 'PUK2', 'IMSI2', 'KI2', 'ATTR1', 'ATTR2', 'ATTR3',
         'ATTR4', 'ATTR5', 'ATTR6', 'ATTR7', 'ATTR8', 'ATTR9', 'ATTR10']

ROOT_PATH = os.path.dirname(os.path.abspath(__file__)).split(os.sep + "Lib")[0]
_TEMPLATE_PATH = os.path.join(ROOT_PATH, "Case", "data", "uploadFile", "Template.txt")

_NECESSARY_KEY_ICCID = 'ICCID'
_NECESSARY_KEY_IMSI = "IMSI"

LINES = ",".join(TITLE) + "\n"


class CardInfoByTxt():

    def __init__(self):
        self.lines = LINES
        self.file_path = _TEMPLATE_PATH
        assert os.path.exists(self.file_path), "Template must be exist!"

    def write_to_txt(self, dict_list: list):
        for dict in dict_list:
            assert self.check_keys(dict)
            self.gen_lines(dict)
        with open(self.file_path, 'w') as f:
            f.write(self.lines)

    def gen_lines(self, dict):
        temp_list = []
        sorted_list = sorted(dict.keys(), key=TITLE.index)
        for k in sorted_list:
            if k in TITLE and sorted_list.index(k) == TITLE.index(k):
                temp_list.append(dict[k])
            else:
                for i in range(int(TITLE.index(k)) - int(sorted_list.index(k))):
                    temp_list.append("")
                temp_list.append(dict[k])
        self.lines += ",".join(temp_list) + "\n"

    def check_keys(self, kwargs: dict):
        assert _NECESSARY_KEY_ICCID in kwargs.keys() and _NECESSARY_KEY_IMSI in kwargs.keys(), "Necessary keys required!"
        for key in kwargs.keys():
            if key not in TITLE:
                return False
        return True

    def generate_card_info(self, ICCID: int, IMSI: int,PIN1,PUK1,PIN2,PUK2,KI,ADM1, num=2):
        i = 0
        cont_list = []
        while i < num:
            dict = {}
            dict["ICCID"] = str(ICCID)
            dict["IMSI"] = str(IMSI)
            dict["PIN1"] = PIN1
            dict["PUK1"] = PUK1
            dict["PIN2"] = PIN2
            dict["PUK2"] = PUK2
            dict["KI"] = KI
            dict["ADM1"] = ADM1
            cont_list.append(dict)
            ICCID = ICCID + 1
            IMSI = IMSI + 1
            i = i + 1
        return cont_list

    def get_content_by_keyword(self, path, keyword: str, sep: str, index: int):
        with open(path, 'r+') as file:
            linesCont = file.readlines()
        for line in linesCont:
            # 等于-1表示匹配不到，非-1表示匹配到的索引
            if line.strip().find(keyword) != -1:
                return line.split(sep)[index].strip()

    def write_to_txt_by_path(self, list, path):
        self.file_path = path
        # imsi = int(self.get_content_by_keyword(self.file_path, 'IMSI', ':', 1))
        # iccid = int(self.get_content_by_keyword(self.file_path, 'Ser_nb', ':', 1))
        # quantity = int(self.get_content_by_keyword(self.file_path, 'Quantity', ':', 1))
        dict_list = list
        with open(self.file_path, 'a') as f:
            for dict in dict_list:
                f.write("{}\n".format(dict['IMSI'] + ' ' + dict['ICCID'] + ' ' + dict['PIN1'] + ' ' + dict['PUK1'] + ' ' \
                                      + dict['PIN2'] + ' ' + dict['PUK2'] + ' ' + dict['KI']))

    def get_card_info_sp(self, input_path, output_path,card_amount,add_var_dict: dict):
        self.file_path = input_path
        card_list = []
        card_message = ''
        with open(self.file_path, "r+") as file:
            line = file.readlines()
            count = len(line)
            message = ''
            for i in range(0, count - card_amount):
                message = message + line[i]
            for i in range(count - card_amount, count):
                line_info = line[i]
                line_info = line_info.strip('\n')
                line_list = line_info.split(' ')
                card_dict = {'IMSI': line_list[0], 'ICCID_F': line_list[1], 'MSISDN': line_list[2]}
                print(card_dict)
                print(type(card_dict))
                for key, value in add_var_dict.items():
                    card_dict[key] = value
                card_list.append(card_dict)
            for item in card_list:
                for value in item.values():
                    card_message = card_message + value + ' '
                card_message = card_message + '\n'
            gen_card_info = message + card_message
        with open(output_path, "w") as output:
            output.write(gen_card_info)
        return card_list

    def gen_goods_info(self, input_path, output_path, goods_info_list: list):
        self.file_path = input_path
        with open(self.file_path, "r+") as file:
            info = file.read()
            spec_goods_info = ''
            for item in goods_info_list:
                if isinstance(item,dict):
                    spec_goods_info = ','.join('%s' % value for value in item.values())
                info = info + "\n" + spec_goods_info
            print(info)
        with open(output_path, "w") as output:
            output.write(info)


    def write_to_txt_dict(self, input_path, output_path, dict: dict,separator):
        self.file_path = input_path
        with open(self.file_path, "r+") as f:
            info = f.read()
            info = info + "\n" + ",".join(dict.values())
            # for value in dict.values():
            #     info = info + value + separator
            # info = info.rstrip(separator)
        with open(output_path, "w") as output:
            output.write(info)


if __name__ == "__main__":
    #CardInfoByTxt().write_to_txt_by_path(r'G:\INP2021010038.out - Blank USIM.txt')
    pass
